package com.weixing.mall.provider.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.support.auth.MemAuth;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.vo.AgentRpcVo;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理跟代理商相关的一些公共业务逻辑，manager的语义可能不够准确，暂时先这么用
 *
 * @author  Small
 * @date   2020/5/16 17:49
 * @since  1.0
 **/
@Component("agentManager")
public class AgentManager {
    @Autowired
    private AgentServiceRpc agentServiceRpc;

    /**
     * 方法描述: 代理下单前校验代理商是否能够下单
     *
     * @Author Small
     * @param agentId       代理自身
     * @param agentChildId  代下单代理
     * @Date 2020/5/24 9:45
     * @return com.weixing.mall.base.wrapper.Result
     */
    public Result<AgentRpcVo> checkAgent(long agentId, Long agentChildId) {
        // 校验自身权限
        Result result = this.checkAgent(agentId, true);
        if (result.isSuccess()) {
            // 如果自身校验通过再去校验是否为下级代理下单
            AgentRpcVo agent = (AgentRpcVo) result.getData();
            if (null != agentChildId) {
                Result result1 = this.checkAgent(agentChildId, true);
                if (result1.isSuccess()) {
                    AgentRpcVo child = (AgentRpcVo) result1.getData();
                    // 校验是否是父子关系
                    if (!checkRelation(agent, child)) {
                        return ResultUtil.error("不能替非自己团队的代理下单");
                    } else {
                        if (child.getAgentLevel().intValue() < agent.getAgentLevel().intValue()) {
                            return ResultUtil.error("不能为比自己等级高的代理下单");
                        }
                    }
                }
                return result1;
            }
        }
        return result;
    }

    private boolean checkRelation(AgentRpcVo agent, AgentRpcVo child) {
        AgentLevelEnum agentLevel = EnumUtil.getIEnum(AgentLevelEnum.class, agent.getAgentLevel());
        Long agentId = agent.getId();
        boolean flag = true;
        switch (agentLevel) {
            case DEALER:
                flag = child.getDealerId().longValue() == agentId;
                break;
            case LEVEL_1:
                flag = child.getLevel1st().longValue() == agentId;
                break;
            case LEVEL_2:
                flag = child.getLevel2nd().longValue() == agentId;
                break;
            case LEVEL_3:
                flag = child.getLevel3rd().longValue() == agentId;
                break;
            case LEVEL_4:
                flag = child.getLevel4th().longValue() == agentId;
                break;
            default:
                break;
        }
        return flag;
    }


    /**
     * 方法描述: 校验代理权限
     *
     * @Author Small
     * @param agentId
     * @Date 2020/5/24 9:49
     * @return com.weixing.mall.base.wrapper.Result
     */
    public Result checkAgent(long agentId, boolean checkLockDate) {
        Result<AgentRpcVo> agentEditVoResult = agentServiceRpc.selectByAgentId(agentId);
        if (!agentEditVoResult.isSuccess()) {
            return ResultUtil.error("服务繁忙，请稍后再试");
        } else {
            AgentRpcVo agentEditVo = agentEditVoResult.getData();
            if (null == agentEditVo) {
                return ResultUtil.error("代理商不存在");
            } else {
                if (IsEnableEnum.DISABLE.getValue().equals(agentEditVo.getIsEnable())) {
                    return ResultUtil.error("代理已被禁用，不能够下单");
                }
                Date now = new Date();
                if (now.compareTo(agentEditVo.getEffectTime()) < 0) {
                    return ResultUtil.error("对不起，代理权益还未生效");
                }
                if (now.compareTo(agentEditVo.getMaturityTime()) > 0) {
                    return ResultUtil.error("对不起，代理权益已到期");
                }
                if (WhetherEnum.NO.getValue().equals(agentEditVo.getIsBind())) {
                    return ResultUtil.error("尚未绑定结构树，不能够下单");
                }

                // 代理下单特殊校验
                if (checkLockDate && StrUtil.isNotEmpty(agentEditVo.getLockDate())) {
                    String format = DateUtil.format(new Date(), com.weixing.mall.base.constant.DatePattern.NORM_DATE_PATTERN);
                    if (StrUtil.equals(agentEditVo.getLockDate(), format)) {
                        return ResultUtil.error("抱歉，今日不能下单");
                    }
                }

            }
        }
        return agentEditVoResult;
    }


    /**
     * 方法描述: 校验代理商
     * @Author Small
     * @param agentId
     * @param agentSn
     * @param agentName
     * @Date 2020/1/10 15:18
     * @return com.weixing.mall.base.wrapper.Result
     */
    public Result<AgentRpcVo> loadAgent(Long agentId, String agentSn, String agentName, MemAuth auth) {
        AgentRpcVo vo = null;
        long aid = 0;
        if (null != agentId) {
            aid = agentId;
        } else if (null != auth.getAid()) {
            aid = auth.getAid();
        } else if (null != auth.getAbid()) {
            aid = auth.getAbid();
        }
        if (0 != aid) {
            return checkAgent(aid, false);
        }
        return ResultUtil.success(vo);
    }

    /**
     * 加载代理商
     *
     * @param agentId      选中的代理id
     * @param auth         会员
     * @date  2020/1/10 15:18
     * @return 代理商信息
     */
    public AgentRpcVo loadAgent(Long agentId, MemAuth auth) {
        AgentRpcVo vo = null;
        long aid = 0;
        if (null != agentId) {
            aid = agentId;
        } else if (null != auth.getAid()) {
            aid = auth.getAid();
        }
        if (0 != aid) {
            Result<AgentRpcVo> result = loadAgent(aid);
            if (result.isSuccess()){
                vo = result.getData();
            }else{
                throw new BusinessException(result.getMsg());
            }
        }
        return vo;
    }


    public AgentRpcVo loadAgentRpcVo(long agentId) {
        Result<AgentRpcVo> agentEditVoResult = agentServiceRpc.selectByAgentId(agentId);
        if (!agentEditVoResult.isSuccess()) {
            throw  new BusinessException("代理服务繁忙，请稍后再试");
        } else {
            AgentRpcVo agentEditVo = agentEditVoResult.getData();
            if (null == agentEditVo) {
                throw  new BusinessException("代理商不存在");
            }
        }
        return agentEditVoResult.getData();
    }

    public Result<AgentRpcVo> loadAgent(long agentId) {
        Result<AgentRpcVo> agentEditVoResult = agentServiceRpc.selectByAgentId(agentId);
        if (!agentEditVoResult.isSuccess()) {
            return ResultUtil.error("代理服务繁忙，请稍后再试");
        } else {
            AgentRpcVo agentEditVo = agentEditVoResult.getData();
            if (null == agentEditVo) {
                return ResultUtil.error("代理商不存在");
            }
        }
        return agentEditVoResult;
    }


    public void updateAgentTradeDate(AgentRpcVo agentRpcVo) {
        if (null != agentRpcVo) {
            String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
            String tradeDate = StringUtil.isBlank(agentRpcVo.getTradeDate()) ? "" : agentRpcVo.getTradeDate();
            if (!tradeDate.equals(today)) {
                agentServiceRpc.updateTradeDate(agentRpcVo.getId(), today);
            }
        }
    }
}
